package com.gy.zpchat.ui.search;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import im.zego.zim.callback.ZIMConversationsSearchedCallback;
import im.zego.zim.callback.ZIMMessagesSearchedCallback;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMMessage;
import im.zego.zim.entity.ZIMConversationSearchConfig;
import im.zego.zim.entity.ZIMConversationSearchInfo;
import im.zego.zim.entity.ZIMMessageSearchConfig;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMMessageOrder;
import im.zego.zim.enums.ZIMMessageType;
import com.gy.zpchat.R;
import com.gy.zpchat.SDKManager;
import com.gy.zpchat.entity.SearchInfo;
import com.gy.zpchat.enums.ChatItemType;
import com.gy.zpchat.enums.MessageLoadType;
import com.gy.zpchat.ui.search.adapter.holder.SearchContentAdapter;

import java.util.ArrayList;
import java.util.List;

public class SearchResultsActivity extends AppCompatActivity
        implements ZIMMessagesSearchedCallback, ZIMConversationsSearchedCallback {

    private static final String TAG = "MainActivity";
    public BottomNavigationView bottomNavigationView;
    public SearchContentAdapter searchContentAdapter;
    public RecyclerView recyclerView;
    public String conversationID;
    public String conversationName;
    public ZIMConversationType conversationType;
    private MessageLoadType messageLoadType;
    private boolean isGlobalSearch;
    private int nextFlag = -1;
    private ZIMMessage nextMessage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        setTitle(getString(R.string.search));

        conversationID = getIntent().getStringExtra("conversationID");
        conversationName = getIntent().getStringExtra("conversationName");
        conversationType = ZIMConversationType.getZIMConversationType(
                getIntent().getIntExtra("conversationType", -1));

        if (conversationID == null) {
            isGlobalSearch = true;
        }


        searchContentAdapter = new SearchContentAdapter(this, isGlobalSearch);
        LinearLayoutManager linearLayoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        linearLayoutManager.setStackFromEnd(false);
        searchContentAdapter.setHasStableIds(true);
        recyclerView = findViewById(R.id.msg_list);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(searchContentAdapter);
        recyclerView.setItemAnimator(null);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                if (lastVisibleItemPosition == searchContentAdapter.getItemCount() - 1) {
                    if (messageLoadType != MessageLoadType.MESSAGE_LOAD_TYPE_LOADING &&
                            messageLoadType != MessageLoadType.MESSAGE_LOAD_TYPE_NO_DATA) {
                        onLoadMsg();
                    }
                }
            }
        });

        if (!isGlobalSearch) {
            SDKManager.sharedInstance().getZim().searchLocalMessages(
                    conversationID, conversationType, getSearchLocalMessageConfig(), SearchResultsActivity.this);
        } else {
            start_time = System.currentTimeMillis();
            SDKManager.sharedInstance().getZim().searchLocalConversations(
                    getGenSearchGlobalMessageConfig(), SearchResultsActivity.this);
        }
    }

    private ZIMConversationSearchConfig getGenSearchGlobalMessageConfig() {
        String searchKeyword = getIntent().getStringExtra("searchKeyword");
        boolean isTextChecked = getIntent().getBooleanExtra("isTextChecked", false);
        boolean isImageChecked = getIntent().getBooleanExtra("isImageChecked", false);
        boolean isAudioChecked = getIntent().getBooleanExtra("isAudioChecked", false);
        boolean isVideoChecked = getIntent().getBooleanExtra("isVideoChecked", false);
        boolean isFileChecked = getIntent().getBooleanExtra("isFileChecked", false);
        String userId = getIntent().getStringExtra("userId");
        long startTimestamp = getIntent().getLongExtra("startTimestamp", 0);
        long endTimestamp = getIntent().getLongExtra("endTimestamp", 0);

        ZIMConversationSearchConfig config = new ZIMConversationSearchConfig();
        config.totalConversationCount = 20;
        config.conversationMessageCount = 10;
        config.keywords.add(searchKeyword);
        if (isTextChecked) {
            config.messageTypes.add(ZIMMessageType.TEXT);
        }
        if (isImageChecked) {
            config.messageTypes.add(ZIMMessageType.IMAGE);
        }
        if (isAudioChecked) {
            config.messageTypes.add(ZIMMessageType.AUDIO);
        }
        if (isVideoChecked) {
            config.messageTypes.add(ZIMMessageType.VIDEO);
        }
        if (isFileChecked) {
            config.messageTypes.add(ZIMMessageType.FILE);
        }

        if (userId != null && !userId.equals("")) {
            config.senderUserIDs = new ArrayList<>();
            config.senderUserIDs.add(userId);
        }
        if (userId != null && !userId.equals("")) {
            config.startTime = startTimestamp;
            config.endTime = endTimestamp;
        }
        return config;
    }

    private ZIMMessageSearchConfig getSearchLocalMessageConfig() {
        String searchKeyword = getIntent().getStringExtra("searchKeyword");
        boolean isTextChecked = getIntent().getBooleanExtra("isTextChecked", false);
        boolean isImageChecked = getIntent().getBooleanExtra("isImageChecked", false);
        boolean isAudioChecked = getIntent().getBooleanExtra("isAudioChecked", false);
        boolean isVideoChecked = getIntent().getBooleanExtra("isVideoChecked", false);
        boolean isFileChecked = getIntent().getBooleanExtra("isFileChecked", false);
        String userId = getIntent().getStringExtra("userId");
        long startTimestamp = getIntent().getLongExtra("startTimestamp", 0);
        long endTimestamp = getIntent().getLongExtra("endTimestamp", 0);

        ZIMMessageSearchConfig config = new ZIMMessageSearchConfig();
        config.count = 10;
        config.order = ZIMMessageOrder.DESCENDING;
        config.keywords.add(searchKeyword);
        if (isTextChecked) {
            config.messageTypes.add(ZIMMessageType.TEXT);
        }
        if (isImageChecked) {
            config.messageTypes.add(ZIMMessageType.IMAGE);
        }
        if (isAudioChecked) {
            config.messageTypes.add(ZIMMessageType.AUDIO);
        }
        if (isVideoChecked) {
            config.messageTypes.add(ZIMMessageType.VIDEO);
        }
        if (isFileChecked) {
            config.messageTypes.add(ZIMMessageType.FILE);
        }

        if (userId != null && !userId.equals("")) {
            config.senderUserIDs.add(userId);
        }
        if (userId != null && !userId.equals("")) {
            config.startTime = startTimestamp;
            config.endTime = endTimestamp;
        }
        return config;
    }

    long start_time;

    protected void onLoadMsg() {
        if (!isGlobalSearch) {
            if(nextMessage == null){
                return;
            }
            ZIMMessageSearchConfig config = getSearchLocalMessageConfig();
            config.nextMessage = this.nextMessage;
            SDKManager.sharedInstance().getZim().searchLocalMessages(
                    conversationID, conversationType, config, SearchResultsActivity.this);
        } else {
            if(nextFlag == 0){
                return;
            }
            start_time = System.currentTimeMillis();
            ZIMConversationSearchConfig config = getGenSearchGlobalMessageConfig();
            config.nextFlag = 0;
            SDKManager.sharedInstance().getZim().searchLocalConversations(config
                    , SearchResultsActivity.this);
        }
    }

    public static void actionStart(Activity activity, String conversationID,
                                   String conversationName, int conversationType, String searchKeyword, boolean isTextChecked, boolean isImageChecked, boolean isAudioChecked, boolean isVideoChecked, boolean isFileChecked, String userId, long startTimestamp, long endTimestamp) {
        Intent intent = new Intent(activity, SearchResultsActivity.class);
        intent.putExtra("conversationID", conversationID);
        intent.putExtra("conversationName", conversationName);
        intent.putExtra("conversationType", conversationType);
        intent.putExtra("searchKeyword", searchKeyword);
        intent.putExtra("isTextChecked", isTextChecked);
        intent.putExtra("isImageChecked", isImageChecked);
        intent.putExtra("isAudioChecked", isAudioChecked);
        intent.putExtra("isVideoChecked", isVideoChecked);
        intent.putExtra("isFileChecked", isFileChecked);
        intent.putExtra("userId", userId);
        intent.putExtra("startTimestamp", startTimestamp);
        intent.putExtra("endTimestamp", endTimestamp);
        activity.startActivity(intent);
    }

    @Override
    public void onMessagesSearched(String conversationID, ZIMConversationType conversationType, ArrayList<ZIMMessage> messageList, ZIMMessage nextMessage, ZIMError errorInfo) {
        List<SearchInfo> searchInfos = new ArrayList<>();
        for (int i = 0; i < messageList.size(); i++) {
            SearchInfo searchInfo = new SearchInfo();
            if (messageList.get(i).getSenderUserID().equals(
                    SDKManager.sharedInstance().zimUserInfo.userID)) {
                searchInfo.setType(ChatItemType.CHAT_ITEM_TYPE_RIGHT);
            } else {
                searchInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
            }
            searchInfo.setZIMMessage(messageList.get(i));
            searchInfos.add(searchInfo);
        }
        this.nextMessage  = nextMessage;
        searchContentAdapter.addSearchInfo(searchInfos);
    }

    @Override
    public void onConversationsSearched(ArrayList<ZIMConversationSearchInfo> globalMessageInfoList, int next_flag, ZIMError errorInfo) {
        long end_time = System.currentTimeMillis();
        Log.e("cc==", "搜索耗时：" + (end_time - start_time) + "命中会话条数" +
                globalMessageInfoList.size());
        this.nextFlag = next_flag;
        List<SearchInfo> searchInfos = new ArrayList<>();

        for (int i = 0; i < globalMessageInfoList.size(); i++) {
            SearchInfo searchInfo = new SearchInfo();
            searchInfo.setConversation(globalMessageInfoList.get(i));
            searchInfos.add(searchInfo);
        }
        searchContentAdapter.addSearchInfo(searchInfos);

    }

}
